package lumis.service.wsrp.producer;

import java.util.Set;

import javax.persistence.NoResultException;

import lumis.doui.processaction.ProcessActionHandler;
import lumis.doui.source.TabularSource;
import lumis.doui.source.field.ITabularSourceField;
import lumis.portal.PortalException;
import lumis.portal.UnexpectedException;
import lumis.portal.manager.ManagerFactory;

import com.sun.portal.wsrp.producer.ProducerException;

/**
 * {@link ProcessActionHandler} responsible for deletion of offeredPortletNames
 * of the {@link ProducerImpl} associated with current service instance.
 * 
 * @version $Revision: 11180 $ $Date: 2009-12-04 18:13:02 -0200 (Fri, 04 Dec 2009) $
 * @since 5.5.0
 */
public class ProducerAdministrationListDeleteProcessActionHandler extends ProcessActionHandler<TabularSource<ITabularSourceField>>
{
	public void processAction() throws PortalException
	{
		// get the deleted items
		String[] serviceInterfaceInstanceIds = getParameter("serviceInterfaceInstanceId", String[].class);
		if (serviceInterfaceInstanceIds != null && serviceInterfaceInstanceIds.length > 0)
		{
			// get the producer associated with current service instance
			ProducerImpl producer;
			try
			{
				producer = (ProducerImpl) ManagerFactory.getEntityManager().createNamedQuery(
						ProducerImpl.NAMED_QUERY_FIND_PRODUCER_BY_NAMESPACE).setParameter("namespace",
						douiContext.getRequest().getServiceInstanceConfig().getId()).getSingleResult();
			}
			catch (NoResultException e)
			{
				producer = null;
			}

			// update the producer removing the deleted offeredPortletNames
			try
			{
				Set<String> producerKeys = producer.getOfferedPortletNames();
				for (String serviceInterfaceInstanceId : serviceInterfaceInstanceIds)
				{
					if (producerKeys.contains(serviceInterfaceInstanceId))
						producerKeys.remove(serviceInterfaceInstanceId);
				}
				producer.setOfferedPortletNames(producerKeys);
				ManagerFactory.getEntityManager().persist(producer);
			}
			catch (ProducerException e)
			{
				throw new UnexpectedException(e);
			}
		}
		addDefaultResponse();
	}
}
